package serwers;

import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;

/**
 *
 * For only now if someone connects to the server it will create a new thread to
 * take care of the client.
 */
public class Server implements Runnable {

	/**
	 * Private variables to make our server work.
	 */
	private int serverport = 8000;
	private ServerSocket serversocket = null;
	private boolean stop = false;
	public Server(int port) {
		this.serverport = port;
	}

	public void run() {
		synchronized (this) {
			Thread.currentThread();
		}
		openServerSocket();
		while (!stop()) {
			// accepting connections here
			Socket clientSocket = null;
			try {
				clientSocket = this.serversocket.accept();
			} catch (IOException e) {
				if (stop()) {
					System.out.println("Server has stopped");
					return;
				}
				throw new RuntimeException("error while accepting connection",
						e);
			}
			/**
			 * The new thread is created here
			 */
			new Thread(new WorkerRunnable(clientSocket, "ThreadedServer"))
					.start();
		}
		System.out.println("Server stopped");

	}

	/**
	 *
	 * Stopping server socket
	 */
	private synchronized boolean stop() {
		return this.stop;
	}

	/**
	 * Opening server socket
	 */
	private void openServerSocket() {
		try {
			this.serversocket = new ServerSocket(this.serverport);
		} catch (IOException e) {
			throw new RuntimeException("cannot open port", e);
		}
	}

	/**
	 *
	 * Our main function to start server I'm thinking of actually starting a
	 * server with an argument describing how many players are allowed to
	 * connect, it's like server will be waiting for at least 2 players. Other
	 * idea is that we can make something like watch I mean if nobody has
	 * connected during a time period server will automatically close. Under one
	 * exception (arguable) : If there's one player already connected he will be
	 * asked to play with bot. Player shall be able to respond with 'Y/N'
	 * message.
	 */
	public static void main(String[] args) {
		Server serv = new Server(9000);
		System.out.println("Server has been opened");
		serv.run();
		/**
		 * This function is closing server
		 */
		// serv.stop();
	}

}
